package Demo1;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class deleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");

        int count = 0;
        // 获取这里的前端部门编号
        String dno = req.getParameter("deptno");
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DBUtil.getConnection();

            // 开始事务
            connection.setAutoCommit(false);
            String sql = "delete from dept where deptno = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, dno);
            count = preparedStatement.executeUpdate();
            connection.commit();
        } catch (SQLException e) {
            // 事务回滚
            if (connection != null) {
                try {
                    connection.rollback();
                } catch (SQLException ex) {
                    e.printStackTrace();
                }
            }

            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection, preparedStatement, null);
        }
        // 检测是否删除成功 假若这里的count是1那么就是删除成功
        if(count == 1){
            // 删除成功就跳转到listServlet页面.
            // 跳转到path指定路径.
//            req.getRequestDispatcher("/dept/list").forward(req,resp);
            // 重定向的时候要加项目名
            resp.sendRedirect(req.getContextPath()+"/dept/list");
        }else {
            // 删除失败
//            req.getRequestDispatcher("/Delerror.html").forward(req,resp);
            resp.sendRedirect(req.getContextPath()+"/Delerror.html");
        }
    }
}